package com.lvmama.rhino.web;

import com.lvmama.rhino.enums.CommonType;
import com.lvmama.rhino.pojo.StatisticCode;
import com.lvmama.rhino.pojo.TaskSequence;
import com.lvmama.rhino.service.StatisticCodeService;
import com.lvmama.rhino.service.TaskSequenceService;
import com.lvmama.rhino.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.lvmama.rhino.utils.HttpSignUtil.getSignFromMap;


@Controller
@RequestMapping("httpserver")
public class HttpServerController extends BaseController {


    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Autowired
    private StatisticCodeService statisticCodeService;

    @Autowired
    private TaskSequenceService taskSequenceService;

    /**
     * 提供httpserver服务，返回已校验完成的code码
     * @return
     */
    @RequestMapping("getCode") //处理http请求
    public @ResponseBody Map<String, String> httpServer(
            HttpServletRequest request,
            @RequestParam(value = "type", required = false)String type,
            @RequestParam(value = "name", required = false)String name,
            @RequestParam(value = "enName", required = false)String enName,
            @RequestParam(value = "cname", required = false)String cname,
            @RequestParam(value = "dname", required = false)String dname)throws Exception{

        
        Map<String, String> result = getResult();
        if(type == null || type.isEmpty() || type.equals("")) {
            result.put("code","The type is empty");
            result.put("state", "error");
            return result;
        }
        
        /*校验签名是否正确*/
        /*if (!MD5Utils.check(request)) {
            result.put("code","Check failure");
            result.put("state", "error");
            return result;
        }*/
        
        //校验级别码
        String levelCode = LevelCode.getLevelCode(type);
        JedisTemplate jtr = JedisTemplate.getReaderInstance();
        JedisTemplate jtw = JedisTemplate.getWriterInstance();
        //类型为页面专题
        if(levelCode.equals("3zhTi")){
            if(name == null || name.isEmpty() || name.equals("")) {
                result.put("code","The name is empty");
                result.put("state", "error");
                return result;
            }
            
            if(enName == null || enName.isEmpty() || enName.equals("")) {
                result.put("code","The enName is empty");
                result.put("state", "error");
                return result;
            }
            
            String realMsgCode = jtr.get("codeName_"+name) == null ? "" : jtr.get("codeName_"+name).toString();
            if(!isEmptyString(realMsgCode)){
                result.put("code",realMsgCode);
                result.put("state", "success");
                return result;
            }
            
            
            //查询名称为name的code是否存在
            int isExist = statisticCodeService.getCountForName(name) == 0 ? 0 : statisticCodeService.getCountForName(name);
            if(isExist != 0){
                StatisticCode existStatisticCode = new StatisticCode();
                existStatisticCode.setName(name);
                existStatisticCode=statisticCodeService.selectStatisticCode(existStatisticCode);
                jtw.set("codeName_"+name, existStatisticCode.getCode());
                result.put("code",existStatisticCode.getCode());
                result.put("state", "success");
                return result;
            }
            
            //查询获得所有专题code码信息
            List<String> codesList = statisticCodeService.getZhtiLikeCode(levelCode);
            //判断code码是否用完
            if(codesList.size()>=Math.pow(EncryptionKey.s.length, 3)){
                result.put("code","code use up");
                result.put("state", "error");
                return result;
            }
            
            EncryptionKey encryptionKey = new EncryptionKey();
            //校验随机码是否存在，如果存在重新生成
            String pageCode = encryptionKey.validateCode(codesList, levelCode,3);
            
            StatisticCode statisticParentCode = new StatisticCode();
            StatisticCode statisticCode = new StatisticCode();
            statisticParentCode.setCode(levelCode);
            //获得父级code码对象
            statisticParentCode = statisticCodeService.selectStatisticCode(statisticParentCode);
            statisticCode.setEnName(enName);
            statisticCode.setParent(statisticParentCode);
            statisticCode.setIsAdd(CommonType.DISSHOW.getStringValue());
            statisticCode.setCode(pageCode);
            statisticCode.setName(name);
            statisticCode.setCodeType(EncryptionKey.CODETYPE_PAGE);
            statisticCode.setCodeTypeLevel("P3");
            TaskSequence taskSequence = new TaskSequence();
            taskSequenceService.insertTaskSeqence(taskSequence);
            statisticCode.setId(taskSequence.getId());
            int id = statisticCodeService.insertOtherStatisticCodeObj(statisticCode);
            //插入失败返回错误
            if(id == 0){
                result.put("code","0");
                result.put("state", "error");
            }else{
                jtw.set("codeName_"+name, pageCode);
                result.put("code", pageCode);
                result.put("state", "success");
            }
        //类型是渠道和设备
        }else if(levelCode.equals("自有渠道")){
            if(cname == null || cname.isEmpty() || cname.equals("")) {
                result.put("code","The cname is empty");
                result.put("state", "error");
                return result;
            }
            
            if(dname == null || dname.isEmpty() || dname.equals("")) {
                result.put("code","The dname is empty");
                result.put("state", "error");
                return result;
            }
            
            //校验签名是否正确
            if (!MD5Utils.check(request)) {
                result.put("code","Check failure");
                result.put("state", "error");
                return result;
            }
            
            //当dname不为如下版本时,则跳出
            /*if(!dname.equals("ios7.8.1") && !dname.equals("ios7.8.2") && !dname.equals("ios7.8.3") && 
                !dname.equals("android7.8.1") && !dname.equals("android7.8.2") && !dname.equals("android7.8.3")){
                result.put("code","The dname is error");
                result.put("state", "error");
                return result;
            }*/
            //正则表达式过滤
            /*Pattern pattern=Pattern.compile(LevelCode.regexDevice);
            Matcher matcher=pattern.matcher(dname);
            if(!matcher.find()){
                result.put("code","The dname is error");
                result.put("state", "error");
                return result;
            }*/
            
            String realChannelCode = jtr.get("codeName_"+cname) == null ? "" : jtr.get("codeName_"+cname).toString();
            String realDeviceCode = jtr.get("codeName_"+dname) == null ? "" : jtr.get("codeName_"+dname).toString();
            if(!isEmptyString(realChannelCode) && !isEmptyString(realDeviceCode)){
                result.put("channelCode",realChannelCode);
                result.put("deviceCode",realDeviceCode);
                result.put("state", "success");
                return result;
            }
            
            String channelCode = null;
            //查询名称为"自有渠道"的code是否存在
            int isExist = statisticCodeService.getCountForName(levelCode) == 0 ? 0 : statisticCodeService.getCountForName(levelCode);
            if(isExist != 0){
                StatisticCode existStatisticCode = new StatisticCode();
                existStatisticCode.setName(levelCode);
                existStatisticCode=statisticCodeService.selectStatisticCode(existStatisticCode);
                channelCode = existStatisticCode.getCode();
                jtw.set("codeName_"+cname, channelCode);
            }
          //查询名称为dname的code是否存在
            int deviceIsExist = statisticCodeService.getCountForName(dname) == 0 ? 0 : statisticCodeService.getCountForName(dname);
            if(deviceIsExist != 0){
                StatisticCode existDeviceStatisticCode = new StatisticCode();
                existDeviceStatisticCode.setName(dname);
                existDeviceStatisticCode=statisticCodeService.selectStatisticCode(existDeviceStatisticCode);
                jtw.set("codeName_"+dname, existDeviceStatisticCode.getCode());
                result.put("channelCode",channelCode);
                result.put("deviceCode",existDeviceStatisticCode.getCode());
                result.put("state", "success");
                return result;
            }
            
            String levelDeviceCode = LevelCode.getLevelCode(LevelCode.TYPE_SHEBEI);
            //查询获得所有专题code码信息
            List<String> codesList = statisticCodeService.getLikeCodes(levelDeviceCode);
            //判断code码是否用完
            if(codesList.size()>=Math.pow(EncryptionKey.s.length, 3)){
                result.put("channelCode",channelCode);
                result.put("deviceCode","code use up");
                result.put("state", "error");
                return result;
            }
            
            EncryptionKey encryptionKey = new EncryptionKey();
            //校验随机码是否存在，如果存在重新生成
            String pageCode = encryptionKey.validateCode(codesList, levelDeviceCode,3);
            
            StatisticCode statisticParentCode = new StatisticCode();
            StatisticCode statisticCode = new StatisticCode();
            statisticParentCode.setCode(levelDeviceCode);
            //获得父级code码对象
            statisticParentCode = statisticCodeService.selectStatisticCode(statisticParentCode);
            statisticCode.setEnName(dname);
            statisticCode.setParent(statisticParentCode);
            statisticCode.setIsAdd(CommonType.DISSHOW.getStringValue());
            statisticCode.setCode(pageCode);
            statisticCode.setName(dname);
            statisticCode.setCodeType(EncryptionKey.CODETYPE_DEVICE);
            statisticCode.setCodeTypeLevel("D2");
            TaskSequence taskSequence = new TaskSequence();
            taskSequenceService.insertTaskSeqence(taskSequence);
            statisticCode.setId(taskSequence.getId());
            int id = statisticCodeService.insertStatisticCodeObj(statisticCode);
            //插入失败返回错误
            //result = id == 0 ? "{ code: 0, state : 'error' }" : "{ channelCode: '"+channelCode+"', deviceCode: '"+pageCode +"', state : 'success' }";
            if(id == 0){
                result.put("code","0");
                result.put("state", "error");
            }else{
                jtw.set("codeName_"+cname, channelCode);
                jtw.set("codeName_"+dname, pageCode);
                result.put("channelCode",channelCode);
                result.put("deviceCode", pageCode);
                result.put("state", "success");
            }
        } else{//传值错误，返回error
            result.put("code","The type error");
            result.put("state", "error");
            return result;
        }
        return result;
    }
    
    public Map<String, String> getResult() {
        Map<String, String> result = new HashMap<String, String>();
        return result;
    }
    
    @RequestMapping("test")
    public ModelAndView pageStatus(){
        return new ModelAndView("application/test");
    }
    
    @RequestMapping("netWork")
    public ModelAndView netWork(){
        return new ModelAndView("networkInfo");
    }
    
    public static boolean isEmptyString(String str) {
        return str == null ? true : str.trim().equals("") ? true : false;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value="network",method= RequestMethod.POST,produces="text/plain;charset=UTF-8") //处理http请求
    public @ResponseBody String forwardGif(HttpServletRequest request,HttpServletResponse response) throws Exception{
        Map<String, Object> params = request.getParameterMap();
        String originParams = getSignFromMap(params);
        HttpsUtil.requestGet("http://rhino.lvmama.com/network/1.gif?" + originParams);
        return "200";
    }

}
